package cn.dslcode.security.config.oauth2;

import cn.dslcode.common.web.WebUtil;
import cn.dslcode.common.web.response.RestResponse;
import cn.dslcode.security.common.OAuth2ResponseCode;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpointAuthenticationFilter;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author dongsilin
 * @version 2018/4/8.
 *          图片验证码Filter
 */
@Slf4j
@Data
public final class CustomCaptchaVerifyFilter extends TokenEndpointAuthenticationFilter {

    /**
     * 验证码字段名称
     */
    private String captchaCodeParameterName;

    /**
     * 建立构造器，排除循环依赖
     * @param authenticationManager
     */
    public CustomCaptchaVerifyFilter(AuthenticationManager authenticationManager, OAuth2RequestFactory oAuth2RequestFactory, String captchaCodeParameterName) {
        super(authenticationManager, oAuth2RequestFactory);
        setAuthenticationEntryPoint(new OAuth2AuthenticationEntryPoint(){
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                log.info("*******************AuthenticationFailureHandler");
                if (authException instanceof UsernameNotFoundException) {
                    WebUtil.output(response, RestResponse.build(OAuth2ResponseCode.username_not_exists), WebUtil.ResponseOutputType.JSON);
                } else if (authException instanceof BadCredentialsException) {
                    WebUtil.output(response, RestResponse.build(OAuth2ResponseCode.password_error), WebUtil.ResponseOutputType.JSON);
                } else {
                    WebUtil.output(response, RestResponse.buildFail("操作失败"), WebUtil.ResponseOutputType.JSON);
                }
            }
        });
        this.captchaCodeParameterName = captchaCodeParameterName;
    }

}